package eoeProject.edenOfEast.page.loginPage.component;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;

import eoeProject.edenOfEast.core.EOEAuthenticatedWebSession;



//@AuthorizeInstantiation("ADMIN")
public class LoginPanel extends Panel {
	private static final long serialVersionUID = 1L;

	private Form<Void> form = new Form<Void>("form");

	private Model<String> passWord = new Model<String>( "");

	private Model<String> userName = new Model<String>("");

	private FeedbackPanel feedback = new FeedbackPanel("feedback");

	private Label message = new Label("message","");


	private BookmarkablePageLink<WebPage> LinkToRegisterForm = new BookmarkablePageLink<WebPage>("linkToRegisterForm",eoeProject.edenOfEast.page.registerForm.Index.class);


    public LoginPanel(String id) {
    	super(id);
    	feedback.setOutputMarkupId(true);
    	message.setOutputMarkupId(true);
    	message.setVisible(false);

	    TextField<String> userNameForm = new TextField<String>("userNameForm", userName);
	    userNameForm.setRequired(true);
	    form.add(userNameForm);
	    PasswordTextField passwordForm = new PasswordTextField("passwordForm", passWord);
	    form.add(passwordForm);
	    form.add(submitButton);
	    form.add(feedback);
	    form.add(message);
	    add(form);

	    add(LinkToRegisterForm.setOutputMarkupId(true));

    }



    private AjaxButton submitButton = new AjaxButton("submit"){
		/**
		 *
		 */
		private static final long serialVersionUID = -2942520388218435030L;

		@SuppressWarnings("rawtypes")
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form form){
			 setResponsePage(form.getPage());
			if(EOEAuthenticatedWebSession.get().authenticate(userName.getObject(), passWord.getObject()))
				setResponsePage(new eoeProject.edenOfEast.page.topPage.Index());
			else{
				message = new Label("message","*ユーザー名、もしくはパスワードが間違っています。");
				message.setOutputMarkupId(true);
				message.setVisible(true);
				form.addOrReplace(message);
			}
		}

		@SuppressWarnings({ "rawtypes" })
		@Override
         protected void onError(final AjaxRequestTarget target, final Form form) {
			target.add(feedback);
		 }
	};
}
